package com.example.holes;

import android.os.Handler;
import android.content.Context;
import android.graphics.Point;
import android.support.v4.view.MotionEventCompat;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/*
 * The View for the game. Starts a SurfaceHolder thread
 * which writes to the view via lockCanvas()
 */
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
	private SurfaceHolder sh;
	private Context context;
	private GameThread thread;
	private GameEngine gEngine;
	
	public GameView(Context contextS, GameEngine gEngine){
		super(contextS);
		this.context = contextS;
		
		// init holder
		sh = getHolder();
		sh.addCallback(this);
			
		//init game engine
		this.gEngine = gEngine;
		
		// init thread
		thread = new GameThread(sh, context, new Handler(), gEngine);
	    setFocusable(true);
	}
	
	// detects touching the screen and sends the data to the game Engine
	@Override
	public boolean onTouchEvent(MotionEvent event){
		int action = MotionEventCompat.getActionMasked(event);
		if (action == MotionEvent.ACTION_DOWN){
			Point point = new Point((int)event.getRawX(), (int)event.getRawY());
			gEngine.touched(point);
			return true;
		}
		else {
			return super.onTouchEvent(event);
		}
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (thread.getRunning() == false){
			// when game is opened again in the Android OS
			thread = new GameThread(getHolder(), context, new Handler(), gEngine);
			thread.setRunning(true);
			thread.start();
		}
		else{
			// creating GameThread for the first time
			thread.start();
		}
	}
	
	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {}
	
	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		boolean retry = true;
		// code to end gameloop
		thread.setRunning(false);
		while (retry){
			try {
				thread.join();
				retry = false;
			} catch (InterruptedException e){}
		}
	}
}
